# 引用其他目录
import sys
sys.path.append("..")

from tools.dbc_file import DbcFile

class DbcFrameDescCpp:

    # template
    tpl_path = None
    tpl = None
    # output hpp
    path = None
    cpp = None

    def __init__(self, path):
        self.tpl_path = "template/src/dbc_frame_desc.cpp"
        self.path = path

    def make_frame_desc(self, dbc):
        index = 0
        for it in dbc.frame_dict:
            frame = dbc.frame_dict[it]
            print("    { 0x%03X, %d, \"%s\" }, /* %d */" % (frame['id'], frame['length'], frame['name'], frame['id']), file=self.cpp)
            index += 1

    def make(self, dbc):
        self.tpl = open(self.tpl_path, 'r')
        self.cpp = open(self.path, 'w')

        line = self.tpl.readline()
        while line != '':
            info = line.split()
            if len(info) > 0 and info[0] == '///' and info[1] == '[TO-BE-GENERATED]' and info[2] == '[FRAME-DESC]':
                # generate code
                print("/// [GENERATED BEGIN] %s" % info[2], file=self.cpp)
                self.make_frame_desc(dbc)
                print("/// [GENERATED END] %s" % info[2], file=self.cpp)
            else:
                # directly copy
                print(line[:-1], file=self.cpp)
            # next line
            line = self.tpl.readline()

        self.cpp.close()
        self.tpl.close()

if __name__ == '__main__':

    dbc_path = "../examples/example1.dbc"
    dbc_file = DbcFile()
    dbc_file.load_file(dbc_path)

    cpp_path = "../code/src/dbc_frame_desc.cpp"
    cpp_gen = DbcFrameDescCpp(cpp_path)
    cpp_gen.make(dbc_file)

